﻿using Microsoft.Extensions.Hosting;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQPlugin
{
    public class RabbitMQConsumerService : IHostedService
    {
        IConnection con;
        IModel channel;
        public void BaseConsumer(string ququeName)
        {
            con = new RabbitMQHelper().GetConnection();
            var channel = con.CreateModel();
            channel.BasicQos(prefetchSize:0, prefetchCount: 1, global: false);

            //如果不存在队列才需要申明队列
            channel.QueueDeclare(ququeName, true, false, false, null);

            var c = new EventingBasicConsumer(channel);
            c.Received += (sender, e) =>
            {
                byte[] msgByt = e.Body.ToArray();
                string message = Encoding.UTF8.GetString(msgByt);
                Console.WriteLine($"BaseConsumer:{message},datetime:{DateTime.UtcNow}");

                channel.BasicAck(e.DeliveryTag, false);
                //channel.BasicNack(e.DeliveryTag, false, requeue: false);//拒绝消息
                //channel.BasicPublish(ququeName,)
                //channel.BasicAcks += Channel_BasicAcks;
            };

            string consumerTag = channel.BasicConsume(ququeName, autoAck: false, c);

        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            BaseConsumer("dirct.exchagne.ddl");
            BaseConsumer("direct_queque_001");
            BaseConsumer("fanout_queue_001");
            BaseConsumer("fanout_queue_002");
            BaseConsumer("fanout_queue_003");

            await Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            channel.Close();
            con.Close();
            return Task.CompletedTask;
        }
    }
}
